// pages/report/report.js
const {
  getReportTypeList,
  saveReport,
  upload,
  getCenterList,
  getGarbageList,
} = require('../../utils/api');
const { getTownData, validateFields } = require('../../utils/tool');
let typeList = []; // 报备类型列表
let garbageList = [];
let centerList = [];
const rules = {
  type: '请选择报备类型',
  contact: '请填写联系人',
  phone: '请填写联系电话',
  gis: '请选择地理位置',
  town: '请选择街道',
  address: '请填写详细地址',
  imgs: '请上传图片',
};

Page({
  data: {
    typeName: '', // 报备类型名称
    type: '', // 报备类型
    contact: '', // 联系人
    phone: '', //  联系电话
    gisName: '', // 地理位置名称
    gis: '', //  地理位置
    town: '', // 街道
    address: '', // 详细地址
    imgs: [], // 图片列表
    remark: '', // 其他说明
    garbage: '', // 垃圾点id
    center: '', // 处理中心id
    showPopup: false,
    showTypePopup: false,
    roleKey: wx.getStorageSync('roleKey'),
    pickerColumns: [],
    pickerKey: '',
    pickerCurrent: '',
  },

  onLoad() {
    getReportTypeList().then((res) => {
      typeList = res?.data || [];
    });
  },

  handleShowMap() {
    wx.authorize({
      scope: 'scope.userLocation',
      success: async () => {
        const gis = this.data.gis;
        let longitude = '';
        let latitude = '';
        if (gis) {
          const g = gis ? gis.split(',') : [];
          longitude = g?.[0];
          latitude = g?.[1];
        } else {
          const pos = await new Promise((resolve) => {
            wx.getLocation({
              success: (res) => {
                resolve(res);
              },
            });
          });
          longitude = pos?.longitude || '';
          latitude = pos?.latitude || '';
        }
        wx.chooseLocation({
          longitude: longitude || '',
          latitude: latitude || '',
          success: (res) => {
            this.setData({
              gis: `${res.longitude},${res.latitude}`, //  GIS
              gisName: res.address,
            });
          },
          fail: (res) => {
            console.log(res);
          },
        });
      },
    });
  },

  handleAfterRead(e) {
    const { file } = e.detail;
    wx.showLoading({ title: '上传中...', mask: true });
    upload(file.url)
      .then((res) => {
        wx.hideLoading();
        this.setData({
          imgs: [...this.data.imgs, { url: res.url }],
        });
      })
      .catch(() => {
        wx.showToast({ title: '上传失败', icon: 'error' });
      });
  },

  handleDelete(e) {
    const { index } = e.detail;
    this.setData({
      imgs: this.data.imgs.filter((_, i) => i !== index),
    });
  },

  handlePickerClick(e) {
    const { key } = e.currentTarget.dataset;
    let pickerColumns = [];
    let pickerKey = '';
    switch (key) {
      case 'typeName':
        pickerColumns = typeList;
        pickerKey = 'dictLabel';
        break;
      case 'town':
        pickerColumns = getTownData();
        pickerKey = '';
        break;
      case 'garbage':
        pickerColumns = garbageList;
        pickerKey = 'address';
        break;
      case 'center':
        pickerColumns = centerList;
        pickerKey = 'name';
        break;
    }

    this.setData({
      pickerColumns,
      pickerKey,
      showPopup: true,
      pickerCurrent: key,
    });
  },

  getListByTown(townName) {
    getCenterList({ townName }).then((res) => {
      centerList = res.data || [];
    });
    getGarbageList({ townName }).then((res) => {
      garbageList = res.data || [];
    });
  },

  onConfirm(e) {
    const { value } = e.detail;
    const { pickerCurrent } = this.data;
    switch (pickerCurrent) {
      case 'typeName':
        this.setData({
          type: value?.dictType,
          typeName: value?.dictLabel,
          showPopup: false,
        });
        break;
      case 'town':
        this.setData({
          town: value,
          showPopup: false,
        });
        this.getListByTown(value);
        break;
      case 'garbage':
        this.setData({
          garbageName: value.address,
          garbage: value.id,
          showPopup: false,
        });
        break;
      case 'center':
        this.setData({
          centerName: value.name,
          center: value.id,
          showPopup: false,
        });
        break;
    }
  },

  onCancel() {
    this.setData({
      showPopup: false,
    });
  },

  handleSubmit() {
    const params = {
      type: this.data.type,
      contact: this.data.contact,
      phone: this.data.phone,
      gis: this.data.gis,
      province: '江苏省', // 省
      city: '连云港市', // 市
      county: '东海县', // 区县
      town: this.data.town,
      address: this.data.address,
      imgs: this.data.imgs.map((img) => img.url)?.join?.(','),
      remark: this.data.remark,
      garbage: this.data.garbage,
      center: this.data.center,
    };

    if (!validateFields(params, rules)) {
      return;
    }
    saveReport(params).then(() => {
      wx.showToast({ title: '提交成功', icon: 'success' });
      setTimeout(() => {
        wx.navigateBack();
      }, 2000);
    });
  },
});
